package com.example.demo.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Controller
public class MockController {

    @Autowired
    private AmqpTemplate amqpTemplate;

    public volatile static boolean pay = false;

    @RequestMapping("")
    public String index() {
        return "pay";
    }

    @PostMapping("restore")
    @ResponseBody
    public Map restore() {
        pay=false;
        return new HashMap();
    }


    @PostMapping("pay")
    @ResponseBody
    public Map pay() {
        Map map=new HashMap();
        if(pay){
            map.put("result",false);
            return map;
        }else {
            pay=true;
            map.put("result",true);
            return map;
        }

    }


    @PostMapping("sendmq")
    @ResponseBody
    public Map sendmq() {

        try {
            //发送5秒的延时消息
            sendmq(15);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new HashMap();
    }

    public String sendmq(Integer second) throws UnsupportedEncodingException {
        log.info("还有" + second + "秒需要付钱");
        final MessageProperties messageProperties = MessagePropertiesBuilder.newInstance()
                // 设置消息的过期时间
                .setHeader("x-delay", second * 1000)
                .setContentEncoding("utf-8")
                .build();

        final Message message = MessageBuilder
                .withBody(("还有" + second + "秒需要付钱").getBytes("utf-8"))
                .andProperties(messageProperties)
                .build();

        amqpTemplate.send("ex.delayed", "key.delayed", message);

        return "已经下单等待付款";
    }

}
